package com.haiheng.voiceandbook.utils.read;

import android.app.Activity;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.SimplePopupWindow;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.text.view.ZLTextWordCursor;

/**
 * @Des:
 * @Author: hwz
 * @Date:2021/12/20 0020
 * @Version: 1.0
 */
abstract class ReadPopupPanel  extends ZLApplication.PopupPanel {
    public ZLTextWordCursor StartPosition;

    protected volatile SimplePopupWindow myWindow;
    private volatile FBReader myActivity;
    private volatile RelativeLayout myRoot;

    ReadPopupPanel(FBReaderApp fbReader) {
        super(fbReader);
    }

    protected final FBReaderApp getReader() {
        return (FBReaderApp)Application;
    }

    @Override
    protected void show_() {
        if (myActivity != null) {
            createControlPanel(myActivity, myRoot);
        }
        if (myWindow != null) {
            myWindow.show();
        }
    }

    @Override
    protected void hide_() {
        if (myWindow != null) {
            myWindow.hide();
        }
    }

    private final void removeWindow(Activity activity) {
        if (myWindow != null && activity == myWindow.getContext()) {
            final ViewGroup root = (ViewGroup)myWindow.getParent();
            myWindow.hide();
            root.removeView(myWindow);
            myWindow = null;
        }
    }

    public static void removeAllWindows(ZLApplication application, Activity activity) {
        for (ZLApplication.PopupPanel popup : application.popupPanels()) {
            if (popup instanceof ReadPopupPanel) {
                ((ReadPopupPanel)popup).removeWindow(activity);
            }
        }
    }

    public static void restoreVisibilities(ZLApplication application) {
        final ZLApplication.PopupPanel popup = application.getActivePopup();
        if (popup instanceof ReadPopupPanel) {
            ((ReadPopupPanel)popup).show_();
        }
    }

    public final void initPosition() {
        if (StartPosition == null) {
            StartPosition = new ZLTextWordCursor(getReader().getTextView().getStartCursor());
        }
    }

    public final void storePosition() {
        if (StartPosition == null) {
            return;
        }

        final FBReaderApp reader = getReader();
        if (!StartPosition.equals(reader.getTextView().getStartCursor())) {
            reader.addInvisibleBookmark(StartPosition);
            reader.storePosition();
        }
    }

    public void setPanelInfo(FBReader activity, RelativeLayout root) {
        myActivity = activity;
        myRoot = root;
    }

    public abstract void createControlPanel(FBReader activity, RelativeLayout root);
}

